<template>
  <div class="login-page">
    <el-card>
      <template #header>黑马面经运营后台</template>

      <el-form :rules="rules" :model="form" ref="form">
        <el-form-item label="用户名：" prop="username">
          <el-input
            placeholder="请输入用户名"
            v-model="form.username"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码：" prop="password">
          <el-input
            placeholder="请输入密码"
            v-model="form.password"
            type="password"
          ></el-input>
        </el-form-item>
        <el-form-item class="tc">
          <el-button type="primary" @click="userLogin">登录</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { login } from '@/api/user'

export default {
  name: 'LoginIndex',
  data () {
    return {
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 5,
            max: 11,
            message: '用户名长度在 5 到 11 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            pattern: /^\w{5,10}$/,
            message: '密码长度在 5 到 10 个字符',
            trigger: 'blur'
          }
        ]
      },
      form: {
        username: '',
        password: ''
      }
    }
  },
  methods: {
    async userLogin () {
      // 回调函数的方式
      // this.$refs.form.validate((flag, obj) => {
      //   console.log(flag)
      //   console.log(obj)
      // })

      try {
        await this.$refs.form.validate()

        const { data } = await login(this.form)

        // 修改vuex的token
        this.$store.commit('user/updateToken', data.token)

        // 跳转路由
        this.$router.push('/')
      } catch (error) {
        console.log(error)
      }
    },
    // 重置表单
    resetForm () {
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
// .box-card {
//   width: 420px;
//   margin: 0 auto;
// }

//element中组件有一个跟组件名一样的class类名
.login-page {
  min-height: 100vh;
  background: url(@/assets/login-bg.svg) no-repeat center / cover;
  display: flex;
  align-items: center;
  justify-content: space-around;
  .el-card {
    width: 420px;
    ::v-deep .el-card__header {
      height: 80px;
      background: rgba(114, 124, 245, 1);
      text-align: center;
      line-height: 40px;
      color: #fff;
      font-size: 18px;
    }
  }
  .el-form {
    padding: 0 20px;
  }
  .tc {
    text-align: center;
  }
}
</style>
